package com.hhw.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUpload {
		//上传文件绑定到MultipartFile
	@RequestMapping("uploadForm")
	public String  uploadForm(){
		return "uploadForm";
	}
	
	@PostMapping(value="/upload")
	public String upload(HttpServletRequest request,
			@RequestParam("description")  String  description,
			@RequestParam("file")   MultipartFile file)  throws Exception{
		   System.out.println(description);
		//如果文件不为空，写入上传路径
		if(!file.isEmpty()){
			//上传文件路径
			String path=request.getServletContext().getRealPath("/images");
			//区分相同文件名字使用UUID
			/*String str=UUID.randomUUID().toString();*/
			//上传文件名
			String filename=file.getOriginalFilename();
			File filepath=new File(path,filename);
			//判断路径是否存在，如果不存在就创建一个
			if(!filepath.getParentFile().exists()){
				filepath.getParentFile().mkdirs();
			}
			//上传文件保存到一个目标文档中    +str
			file.transferTo(new File(path+File.separator+ filename));
			System.out.println("文件上传路径："+ (path+File.separator+filename));
			request.setAttribute("filename", filename);
			
			
			
//			<<<<<<<<<<<<<<<<<<<<<<<<<<<
			String path2=path+File.separator;
			File file2=new File(path2);
			File[] fil =file2.listFiles();
			List<Object> list=new ArrayList<>();
		for(int i=0;i<fil.length;i++){
			System.out.println("文件名："+fil[i]);

			int i2=fil[i].getPath().lastIndexOf("\\");
			list.add(fil[i].getPath().substring(i2+1));
		}
		    request.setAttribute("list",list);
			return "files";
		}else{
			return "error";
			
		}	
	}
	
}
